const { writeFile, readFile } = require('node:fs/promises')
const fs = require('node:fs')
const path = require('node:path')
const { dialog } = require('electron')

// 通过 window 对象向渲染进程注入 nodejs 能力
window.services = {
  // 选择文件
  async selectFile(filters) {
    const result = await dialog.showOpenDialog({
      properties: ['openFile'],
      filters: filters || [
        { name: '文本文件', extensions: ['txt', 'epub', 'mobi', 'pdf'] }
      ]
    })
    return result
  },
  
  // 读取本地书籍文件
  async readBookFile(filePath) {
    try {
      const stats = fs.statSync(filePath)
      const fileExt = path.extname(filePath).toLowerCase()
      const fileName = path.basename(filePath, fileExt)
      
      // 简单处理txt文件，其他格式可以根据需要扩展
      if (fileExt === '.txt') {
        const content = await readFile(filePath, { encoding: 'utf-8' })
        return {
          success: true,
          fileName,
          fileSize: stats.size,
          fileType: fileExt,
          content,
          path: filePath
        }
      } else {
        return {
          success: false,
          error: '暂不支持该文件格式'
        }
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  },
  // 读文件
  readFile (file) {
    return fs.readFileSync(file, { encoding: 'utf-8' })
  },
  // 文本写入到下载目录
  async writeTextFile (text, filePath) {
    try {
      await writeFile(filePath, text, { encoding: 'utf-8' })
    } catch (error) {
      throw new Error('文件保存失败')
    }
    return filePath
  },
  // 图片写入到下载目录
  writeImageFile (base64Url) {
    const matchs = /^data:image\/([a-z]{1,20});base64,/i.exec(base64Url)
    if (!matchs) return
    const filePath = path.join(window.utools.getPath('downloads'), Date.now().toString() + '.' + matchs[1])
    fs.writeFileSync(filePath, base64Url.substring(matchs[0].length), { encoding: 'base64' })
    return filePath
  },
  pathJoin (...args) {
    return path.join(...args)
  }
}